<?php

class UserTable extends Doctrine_Table 
{
    public function getPager($page=1, $isActive=1, $firstname = null, $phone = null, $username = null, $email = null) 
    {
        $q = Doctrine_Query::create()
                ->select('*')
                ->from('User u')
                ->where('u.id > ?', 0)
                ->orderBy('u.created_at DESC, u.firstname ASC');

        if(in_array($isActive, array('0', '1'))) $q->andWhere('u.is_active = ?', $isActive);

        if($firstname) $q->addWhere("u.firstname LIKE ?", $firstname.'%');

        if($phone) $q->addWhere("u.mobile LIKE ?", $phone);

        if($username) $q->addWhere("u.username LIKE ?", $username.'%');

        if($email) $q->addWhere("u.email LIKE ?", $email.'%');

        $pager = new sfDoctrinePager('User', sfConfig::get('app_pager', 30));
        $pager->setPage($page);
        $pager->setQuery($q);
        $pager->init();

        return $pager;
    }




    public function getUser($username, $password) {
        $q = Doctrine_Query::create()
                ->from('User u')
                ->where('(u.username = ? OR u.email = ?) AND u.password = ?', array($username, $username, md5($password)));
        return $q->fetchOne();
    }

    public function findByUsername($username) {
        $q = Doctrine_Query::create()
                ->from('User u')
                ->where('u.username = ? ', $username);
        return $q->fetchOne();
    }

    public function findByCode($code) {
        $q = Doctrine_Query::create()
                ->from('User u')
                ->where('u.code = ? ', $code);
        return $q->fetchOne();
    }

    public function findByEmail($email) {
        $q = Doctrine_Query::create()
                ->from('User u')
                ->where('u.email = ?', $email);
        return $q->fetchOne();
    }

}